import { useRequest } from "@umijs/hooks";
import { PlusOutlined } from "@ant-design/icons";
import Zmage from "react-zmage";
import cookie from "react-cookies";
import getImgInfo from "../../../../../utils/getImgInfo";
import {
  Button,
  DatePicker,
  Form,
  Input,
  message,
  Select,
  TreeSelect,
  Upload,
} from "antd";
import { Store } from "rc-field-form/lib/interface";
import React, { useEffect, useState } from "react";
import { useSelector } from "react-redux";
import { getOriginString, getSecretString } from "../../../../../utils/encrypt";
import { fetchRequest } from "../../../../../utils/Request";
import { url } from "../../../../../utils/url";
import { useSingleState } from "nice-hooks";

import moment from "moment";

interface ValidateState {
  state: "" | "success" | "warning" | "error" | "validating" | undefined;
  help: string | undefined;
}

interface RequestAddres {
  userId: number;
  userTypeId: string;
  phone: string;
  studentId: string;
  guardianPhone: string;
  photo: string;
  deptId: string;
  startSchoolDate: string;
  graduationDate: string;
  blackCardCode: string;
  wisdomCardImei: any;
  teacherTypeId: string;
}

interface InfoState {
  whiteCard: boolean;
  face: boolean;
  blackCard: boolean;
  blackCardCode: string;
}

export default function EditStudentInformaiton(props: any) {
  const [state, setState] = useSingleState({
    userId: 0,
    userTypeId: "",
    phone: "",
    studentId: "",
    guardianPhone: "",
    photo: "",
    deptId: "",
    teacherTypeId: "",
    startSchoolDate: "",
    graduationDate: "",
    blackCardCode: "",
    fileStoreName: "",
    wisdomCardImei: "",
    credentialsNum: "",
  });

  const uploadButton = (
    <div>
      <PlusOutlined />
      <div className="ant-upload-text">Upload</div>
    </div>
  );

  const { Option } = Select;
  //是否通过Img检测
  const [imgFlag, setImgFlag] = useState(false);
  //是否删除
  const [isDelete, setIsDelte] = useState(false);

  const [status, setStaus] = useState("done");

  const [userTypeList, setUserTypeList] = useState<any>([]);
  const userTypeOptions = userTypeList.map((d: any, index: number) => (
    <Option value={d.userTypeId} key={index}>
      {d.userTypeName}
    </Option>
  ));
  const [validatePhoto, setvalidatePhoto] = useState<ValidateState>({
    state: undefined,
    help: undefined,
  });
  const [photoInfo, setphotoInfo] = useState({
    previewVisible: false,
    previewImage: "",
    previewTitle: "",
    fileList:
      typeof props.info.photo === "undefined" ||
      props.info.photo === "" ||
      props.info.photo === null
        ? []
        : [
            {
              uid: "-1",
              name: props.info.photo,
              status: "done",
              url:
                url.GET_PERSON_FACE_URL +
                "accessToken=" +
                getImgInfo(props.info.photo),
              response: {
                files: [
                  {
                    fileName: props.info.photo,
                    fileStoreName: props.info.photo,
                  },
                ],
              },
            },
          ],
  });

  useEffect(() => {
    getUserTypeRequest({
      teacherTyName: props.info.teacherTyName,
      teacherTypeId: props.info.teacherTypeId,
    });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  async function getUserTypeRequest(params: any) {
    try {
      const json = await fetchRequest(url.GET_USER_TYPE, params);
      if (json.success) {
        setUserTypeList(json.data);
        // form.setFieldsValue({userType:json.data[0].userTypeId})
      } else {
        message.error(json.error);
      }
    } catch (error: any) {
      message.destroy();
      message.error(error.message);
    }
  }

  const getUserType = useRequest(getUserTypeRequest, {
    manual: true,
    loadingDelay: 200,
  });

  //获取redux中的tableData
  const deptData = useSelector((state: any) => {
    const data = state.deptManage.deptData;
    // disableSelect(data)
    return {
      deptData: data,
    };
  });

  //递归修改item的key
  function disableSelect(arr: any[]) {
    arr.map((item) => {
      delete item.disabled;
      item.key = item.deptID;
      item.value = item.deptID;
      if (
        typeof item.children === "undefined" ||
        item.children === null ||
        item.children.length === 0
      ) {
        return;
      } else {
        disableSelect(item.children);
      }
    });
  }

  // const treeData1=disableSelect(treeData)
  const [form] = Form.useForm();

  const layout = {
    labelCol: { span: 5 },
    wrapperCol: { span: 14 },
  };

  const tailLayout = {
    wrapperCol: { offset: 5, span: 14 },
  };
  const editStudent = useRequest(editStudentRequest, {
    manual: true,
    loadingDelay: 200,
  });

  async function editStudentRequest(params: any) {
    try {
      const json = await fetchRequest(url.MODIFY_STUDENT_INFORMATION, params);
      if (json.success) {
        message.success("修改成功!");
        props.onaddSuccess();
      } else {
        message.destroy();
        message.error(json.error);
      }
    } catch (error: any) {
      message.destroy();
      message.error(error.message);
    }
  }

  //科道验证黑金星卡
  const getBlackPhone = useRequest(getBlackPhoneRequest, {
    manual: true,
    loadingDelay: 200,
  });

  async function getBlackPhoneRequest(params: any) {
    try {
      const json = await fetchRequest(url.CHECK_BLACK_CARD_URL, params);
      // console.log("科道返回数据")
      // console.log(json)
      // const blaceCardCode=""
      if (json.success) {
        if (json.isBlackCard && json.isCanApply)
          setState({ ...state, blackCardCode: json.cardCode });
        // setrequestParams({...requestParams,blackCardCode:json.cardCode})
        //科道接口正常才获取地址
        let photo =
          state.fileStoreName === ""
            ? isDelete
              ? ""
              : props.info.photo
            : state.fileStoreName;

        editStudent.run({
          userId: Number(state.userId),
          userTypeId: state.userTypeId,
          phone: state.phone,
          studentId: state.studentId,
          guardianPhone: state.guardianPhone,
          photo: photo,
          deptId: state.deptId,
          wisdomCardImei: state.wisdomCardImei,
          startSchoolDate: state.startSchoolDate,
          graduationDate: state.graduationDate,
          blackCardCode: state.blackCardCode,
          credentialsNum: state?.credentialsNum,
          teacherTypeId: state.teacherTypeId,
        });
      } else {
        message.destroy();
        message.error(json.error);
      }
    } catch (error: any) {
      message.destroy();
      message.error(error.message);
    }
  }

  function onFinish(value: Store) {
    let photo =
      state.fileStoreName === "" ? props.info.photo : state.fileStoreName;

    if (imgFlag) {
      message.error("人脸识别未通过");
      return;
    }

    if (status === "uploading") {
      message.error("请等待上传完成");
      return;
    }

    if (validatePhoto?.state === "validating") {
      message.error("请等待人脸识别完成");
      return;
    }

    if (value.graduationDate > value.startSchoolDate) {
      console.log(props.info.teacherTypeId);
      if (props.info.teacherTypeId !== "0") {
        setState({
          ...state,
          userId: props.info.userId,
          userTypeId: "2",
          teacherTypeId: value.userType,
          studentId: getSecretString(value.studentId),
          phone: getSecretString(value.phone),
          guardianPhone: getSecretString(value.guardianPhone),
          photo: photo,
          deptId: value.deptId,
          wisdomCardImei: value.wisdomCardImei,
          startSchoolDate: moment(value.startSchoolDate).format("YYYY-MM-DD"),
          graduationDate: moment(value.graduationDate).format("YYYY-MM-DD"),
          credentialsNum: getSecretString(value.credentialsNum),
        });
      } else {
        setState({
          ...state,
          userId: props.info.userId,
          userTypeId: value.userType,
          studentId: getSecretString(value.studentId),
          phone: getSecretString(value.phone),
          guardianPhone: getSecretString(value.guardianPhone),
          photo: photo,
          wisdomCardImei: value.wisdomCardImei,
          deptId: value.deptId,
          startSchoolDate: moment(value.startSchoolDate).format("YYYY-MM-DD"),
          graduationDate: moment(value.graduationDate).format("YYYY-MM-DD"),
          credentialsNum: getSecretString(value.credentialsNum),
          teacherTypeId: "",
        });
      }

      getBlackPhone.run({
        userId: props.info.userId,
        userTypeId: value.userType,
        studentId: getSecretString(value.studentId),
        phone: getSecretString(value.phone),
        guardianPhone: getSecretString(value.guardianPhone),
        photo: photo,
        wisdomCardImei: value.wisdomCardImei,
        deptId: value.deptId,
        startSchoolDate: moment(value.startSchoolDate).format("YYYY-MM-DD"),
        graduationDate: moment(value.graduationDate).format("YYYY-MM-DD"),
      });
    } else {
      message.error("毕业时间要大于入学时间");
      return;
    }
  }

  //人脸检测接口
  async function checkUserPhoto(params: any) {
    try {
      setvalidatePhoto({ state: "validating", help: "" });

      const json = await fetchRequest(url.CHECK_FACE_URL, params);
      if (json.success) {
        setvalidatePhoto({ state: "success", help: json.result });
        return Promise.resolve();
      } else {
        setImgFlag(true);
        setvalidatePhoto({ state: "error", help: json.result });
        return Promise.reject(json.result);
      }
    } catch (error: any) {
      setvalidatePhoto({ state: "error", help: "照片验证失败" });
      return Promise.reject("照片验证失败");
    }
  }

  function onFilePreview(value: any) {
    Zmage.browsing({ src: value.url });
  }

  function normFile({ fileList }: any) {
    // console.log('Upload event:', fileList);
    // // return e.fileList;
    if (fileList.length > 0 && fileList[0].status === "done") {
      if (fileList[0].response.success) {
        setState({
          fileStoreName: fileList[0].response.files[0].fileStoreName,
        });
        const myFile = [];
        myFile[0] = {
          ...fileList[0],
          url:
            url.GET_PERSON_FACE_URL +
            "accessToken=" +
            getImgInfo(fileList[0].response.files[0].fileStoreName),
        };
        return myFile;
      } else {
        const myFile = [];
        myFile[0] = {
          ...fileList[0],
          status: "error",
        };
        return myFile;
      }
    } else return fileList;
  }

  //当上传的文件变化的时候
  function onFileChange(info: any) {
    setStaus(info.file.status);

    if (info.file.status === "done") {
      const params = {
        storeName: state.fileStoreName,
      };
      checkUserPhoto(params);
    }
    setphotoInfo({ ...photoInfo, fileList: info.fileList });
  }

  const removePicture = () => {
    setvalidatePhoto({ state: "", help: "" });
    setState({
      fileStoreName: "",
    });

    setImgFlag(false);
    setIsDelte(true);
    setStaus("done");
  };

  return (
    <div>
      <Form
        form={form}
        {...layout}
        onFinish={onFinish}
        initialValues={{
          userName:
            typeof props.info.studentName === "undefined"
              ? ""
              : props.info.studentName,
          userType:
            props.info.teacherTypeId === "0"
              ? props.info.userTypeId
              : props.info.teacherTypeId,
          studentId:
            typeof props.info.studentId === "undefined"
              ? ""
              : props.info.studentId,
          phone:
            typeof props.info.phone === "undefined"
              ? ""
              : getOriginString(props.info.phone),
          guardianPhone:
            typeof props.info.guardianPhone === "undefined"
              ? ""
              : getOriginString(props.info.guardianPhone),
          wisdomCardImei:
            typeof props.info.wisdomCardImei === "undefined"
              ? ""
              : props.info.wisdomCardImei,
          credentialsNum:
            typeof props.info.credentialsNum === "undefined"
              ? ""
              : getOriginString(props.info.credentialsNum),
          deptId:
            typeof props.info.deptId === "undefined" ? "" : props.info.deptId,
          startSchoolDate:
            typeof props.info.startSchoolDate === "undefined" ||
            props.info.startSchoolDate === null ||
            props.info.startSchoolDate === ""
              ? ""
              : moment(props.info.startSchoolDate),
          graduationDate:
            typeof props.info.graduationDate === "undefined" ||
            props.info.graduationDate === null ||
            props.info.graduationDate === ""
              ? ""
              : moment(props.info.graduationDate),
          facePic:
            props.info.photo === "" || props.info.photo === null
              ? []
              : [
                  {
                    uid: "-1",
                    name: props.info.photo,
                    status: "done",
                    url:
                      url.GET_PERSON_FACE_URL +
                      "accessToken=" +
                      getImgInfo(props.info.photo),
                    response: {
                      files: [
                        {
                          fileName: props.info.photo,
                          fileStoreName: props.info.storeName,
                        },
                      ],
                    },
                  },
                ],
        }}
      >
        <Form.Item
          label="姓名"
          name="userName"
          rules={[{ required: true, message: "必须要输入用户名" }]}
        >
          <Input disabled={true} />
        </Form.Item>

        <Form.Item
          label="人员类型"
          name="userType"
          rules={[{ required: true, message: "必须要选择人员类型!" }]}
        >
          <Select
            style={{ width: "100%" }}
            placeholder="请选择人员类型"
            // onChange={typeOnChange}
          >
            {userTypeOptions}
          </Select>
        </Form.Item>

        <Form.Item
          label="联系电话"
          name="phone"
          rules={[
            { required: true, message: "必须要输入手机号码" },
            {
              pattern: /^1[3456789]\d{9}$/,
              message: "手机号码格式错误！",
            },
          ]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="监护人电话"
          name="guardianPhone"
          rules={[
            { pattern: /^1[3456789]\d{9}$/, message: "手机号码格式错误！" },
          ]}
        >
          <Input />
        </Form.Item>
        <Form.Item label="智能学生证卡号" name="wisdomCardImei">
          <Input />
        </Form.Item>
        <Form.Item
          label="学号"
          name="studentId"
          rules={[{ required: true, message: "必须要输入学号" }]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          className="form-control-item"
          name="deptId"
          label="组织机构"
          rules={[{ required: true, message: "必须要选择组织机构" }]}
        >
          <TreeSelect
            className="form-item"
            treeData={deptData.deptData}
            //         treeData={treeData}

            showSearch
            treeNodeFilterProp={"title"}
          />
        </Form.Item>

        <Form.Item
          label="入学时间"
          name="startSchoolDate"
          rules={[{ required: true, message: "必须要选择时间" }]}
        >
          <DatePicker />
        </Form.Item>

        <Form.Item
          label="毕业时间"
          name="graduationDate"
          rules={[{ required: true, message: "必须要选择时间" }]}
        >
          <DatePicker />
        </Form.Item>

        <Form.Item
          label="身份证号"
          name="credentialsNum"
          rules={[
            { required: true, message: "请填写身份证" },
            {
              pattern:
                /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/,
              message: "身份证格式错误！",
            },
          ]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          validateStatus={validatePhoto.state}
          help={validatePhoto.help}
          valuePropName="fileList"
          hasFeedback
          getValueFromEvent={normFile}
          label="人脸照片"
          name="facePic"
        >
          <Upload
            listType="picture-card"
            action={url.UPLOAD_PERSON_URL}
            //@ts-ignore
            // fileList={photoInfo.fileList}
            name={"file"}
            showUploadList={{
              showPreviewIcon: true,
              // showRemoveIcon: canChangePic ? true : false,
              showDownloadIcon: true,
            }}
            onPreview={onFilePreview}
            onRemove={removePicture}
            onChange={onFileChange}
            headers={{ token: cookie.load("collegeToken") }}
            accept=".png,.svg,.jpg,.jpeg,.gif"
          >
            {photoInfo.fileList.length > 0 ? null : uploadButton}
          </Upload>
        </Form.Item>

        <Form.Item {...tailLayout}>
          <Button type="primary" htmlType="submit">
            提交
          </Button>
        </Form.Item>
      </Form>
    </div>
  );
}
